import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import {
	produceLoginApi,
	getPersonLoginInfo,
	loginApi,
	getUserInfo,
	getButtonInfo,
	logoutApi,
	getUnReadMessageApi,
} from "@/api/index";
import { useMenuStore } from "@/stores/useMenuStore";
import { useDictionaryStore } from "@/stores/useDictionaryStore";
import { useProduceStore } from "@/stores/useProduceStore";
import { getTimeState } from "@/utils/common";
import { UserInfo } from "@/types/type";

// const menuStore = useMenuStore()
// const dictionaryStore = useDictionaryStore()
export const useUserStore = defineStore("user", () => {
	// state :userInfo，token，
	const userInfo = reactive<UserInfo>(
		uni.getStorageSync("userInfo") || {
			roles: [], // 预留角色信息
			perms: [], // 按钮权限
			userName: "", // 用户名
			userType: "", // 用户类型
			userId: "", // 用户ID
			loginName: "", // 登录名
			organizationName: "", // 组织机构名称
		}
	);
	const token = ref(uni.getStorageSync("token") || "");
	const tokenTypeStore = ref(uni.getStorageSync("tokenTypeStore") || "");
	const unReadCount = ref(uni.getStorageSync("unReadCount") || 0); // 未读消息条数
	const loginWorkInfo = ref(uni.getStorageSync("loginWorkInfo") || "{}"); // 登录时的工作中心、班组信息
	const ipInfo = ref(uni.getStorageSync("ipInfo") || "{}"); // 登录时的工作中心、班组信息
	// 登录系统
	const loginSystemStore = ref(uni.getStorageSync("loginSystemStore") || "");
	// 默认打印设备
	const defaultPrinter = ref(uni.getStorageSync("defaultPrinter") || "");
	// 当前app版本号
	const currentVersion = ref(uni.getStorageSync("currentVersion") || "");
	// 最新app版本号
	const lastVersion = ref(uni.getStorageSync("lastVersion") || "");
	// 登录账号
	const loginAccount = ref(uni.getStorageSync("loginAccount") || "");
	// 登录密码
	const loginPSW = ref(uni.getStorageSync("loginPSW") || "");
	// actions
	/**
	 * 设置app当前版本号
	 */
	function setCurrentVersion(data) {
		currentVersion.value = data;
		uni.setStorageSync("currentVersion", currentVersion.value);
	}
	/**
	 * 设置app最新版本号
	 */
	function setLastVersion(data) {
		lastVersion.value = data;
		uni.setStorageSync("lastVersion", lastVersion.value);
	}
	/**
	 * 设置登陆系统
	 */
	function setLoginSystemStore(data) {
		loginSystemStore.value = data;
		uni.setStorageSync("loginSystemStore", loginSystemStore.value);
	}
	/**
	 * 设置打印设备
	 */
	function setDefaultPrinter(data) {
		defaultPrinter.value = JSON.stringify(data);
		uni.setStorageSync("defaultPrinter", defaultPrinter.value);
	}
	// action
	/**
	 * 设置工作中心数据
	 */
	function setloginWorkInfo(data) {
		loginWorkInfo.value = JSON.stringify(data);
		uni.setStorageSync("loginWorkInfo", loginWorkInfo.value);
	}
	/**
	 * 设置登录账号
	 */
	function setLoginAccount(data) {
		loginAccount.value = data;
		uni.setStorageSync("loginAccount", loginAccount.value);
	}
	/**
	 * 设置登录密码
	 */
	function setLoginPSW(data) {
		loginPSW.value = data;
		uni.setStorageSync("loginPSW", loginPSW.value);
	}
	/**
	 * 登录
	 */
	function login(data,url='') {
		return new Promise((resolve, reject) => {
			loginApi(data)
				.then(async (res: any) => {
					if (res.code === 200) {
						const { accessToken, tokenType } = res.data;
						token.value = accessToken;
						tokenTypeStore.value = tokenType;
						// 本地存储
						uni.setStorageSync("tokenTypeStore", tokenType);
						uni.setStorageSync("token", accessToken);
						const resInfo: any = await getPersonLoginInfo();
						// 如果是DKIA项目，则记录登录信息
						if (loginSystemStore.value === "app:mes") {
							uni.showToast({
								title: "生产计划登录",
							});
							const produceInfo: any = await produceLoginApi({
								...resInfo.data,
							});
							// 保存登录时的工作中心、班组信息
							loginWorkInfo.value = JSON.stringify(resInfo.data);
							useProduceStore().setCrewMemberList(
								produceInfo.data
							);
							uni.setStorageSync(
								"loginWorkInfo",
								loginWorkInfo.value
							);
						}
						await getInfo();
						await getButtonPermission();
						await useMenuStore().getHomeMenu();
						await useDictionaryStore().getDictionaryList();
						// 获取未读消息
						await getUnReadMessage();
						
						
						
						
						uni.showToast({
							title: userInfo.userName + ", " + getTimeState(),
							icon: "none",
						});
						resolve(200);
						// if (loginSystemStore.value === "DKIA-MES") {
						// 	await getWorkerCenterData();
						// }
						// 非自动登录跳转到首页，自动登录跳转到url页面
						if (url) {
							uni.navigateTo({
								url: "/" + url,
							});
						} else {
							// 跳转到首页
							uni.switchTab({
								url: "/pages/index/index",
							});
						}
						
						
						
						
						// uni.switchTab({
						// 	url: "/pages/index/index",
						// });
						
						
						
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
						});
						reject("error");
					}
				})
				.catch(() => {
					reject("error");
				});
		});
	}
	/**
	 获取信息(用户昵称、头像、角色集合、权限集合)
	 */
	function getInfo() {
		return new Promise((resolve, reject) => {
			getUserInfo()
				.then(({ data }) => {
					if (!data) {
						reject("校验失败，请重新登录");
						return;
					}
					const {
						userName,
						userType,
						userId,
						loginName,
						organizationName,
					} = data as UserInfo;
					Object.assign(userInfo, {
						...userInfo,
						userName,
						userType,
						userId,
						loginName,
						organizationName,
					});
					uni.setStorageSync("userInfo", userInfo);
					resolve(data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}
	/**
	 获取按钮权限信息
	 */
	function getButtonPermission() {
		return new Promise((resolve, reject) => {
			getButtonInfo()
				.then(({ data }) => {
					Object.assign(userInfo, { ...userInfo, perms: data });
					uni.setStorageSync("userInfo", userInfo);
					resolve(data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}
	/**
	 注销
	 */
	function logout() {
		return new Promise<void>((resolve, reject) => {
			setLoginAccount('');
			setLoginPSW('');
			logoutApi()
				.then(() => {
					reLogin();
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	}
	/**
	 清空缓存
	 */
	function resetStore() {
		token.value = "";
		tokenTypeStore.value = "";
		Object.assign(userInfo, {
			roles: [],
			perms: [],
			userName: "",
			userType: "",
			userId: "",
			loginName: "",
			organizationName: "",
		});
		// 清空登录时的工作中心、班组信息
		loginWorkInfo.value = "";
		uni.setStorageSync("loginWorkInfo", "");
		// 清空加工单数据
		useProduceStore().setWorkOrderList([]);
		uni.setStorageSync("workOrderList", "[]");
		// 清空班组成员数据
		useProduceStore().setCrewMemberList([]);
		uni.setStorageSync("crewMemberList", "[]");
		// uni.showToast({
		// 	title: '清缓存啦~',
		// 	icon: 'none'
		// })
		// 清除本地缓存
		// 清空版本号信息
		setCurrentVersion("");
		setLastVersion("");
		// 存储打印设备 & 登录系统
		let printer = defaultPrinter.value;
		let loginSystem = loginSystemStore.value;
		let loginAccount_elder = loginAccount.value;
		let loginPSW_elder = loginPSW.value;
		try {
			uni.clearStorageSync();
			printer && setDefaultPrinter(JSON.parse(printer));
			loginSystem && setLoginSystemStore(loginSystem);
			loginAccount_elder && setLoginAccount(loginAccount_elder);
			loginPSW_elder && setLoginPSW(loginPSW_elder);
		} catch (e) {
			// error
		}
		// uni.clearStorage()
		// App端示例（以安卓为例）
		// #ifdef APP-PLUS
		if (uni.getSystemInfoSync().platform === "android") {
			// 调用原生API清除缓存，需要使用plus对象，确保在#ifdef APP-PLUS环境下运行
			// 注意：这里的代码只是示例，具体实现需要根据你的项目情况和需求来编写
			plus.cache.clear(
				function () {
					console.log("缓存清除成功！");
				},
				function (error) {
					console.error("缓存清除失败: " + error.message);
				}
			);
		}
		// #endif
	}

	function reLogin() {
		resetStore();
		uni.redirectTo({
			url: "/pages/login/accountLogin",
		});
	}

	/**
	 获取已读未读消息
	*/
	function getUnReadMessage() {
		return new Promise((resolve, reject) => {
			getUnReadMessageApi()
				.then(({ data }: any) => {
					unReadCount.value = Math.round(data);
					resolve(data);
				})
				.catch((error: any) => {
					reject(error);
				});
		});
	}
	/**
	 * 设置ip信息
	 */
	function setIpInfo(data) {
		ipInfo.value = JSON.stringify(data);
		uni.setStorageSync("ipInfo", ipInfo.value);
	}

	return {
		logout,
		currentVersion,
		lastVersion,
		setCurrentVersion,
		setLastVersion,
		reLogin,
		loginSystemStore,
		setLoginSystemStore,
		defaultPrinter,
		setDefaultPrinter,
		setloginWorkInfo,
		resetStore,
		ipInfo,
		setIpInfo,
		loginWorkInfo,
		token,
		userInfo,
		tokenTypeStore,
		login,
		getUnReadMessage,
		unReadCount,
		loginAccount,
		loginPSW,
		setLoginAccount,
		setLoginPSW
		
	};
});
